package org.example.educenter.controller;

import com.google.gson.Gson;
import org.example.ResultCode.JwtUtils;
import org.example.educenter.entity.UcenterMember;
import org.example.educenter.service.UcenterMemberService;
import org.example.educenter.utils.ConstantWxUtils;
import org.example.educenter.utils.HttpClientUtils;
import org.example.exceptionHandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Autowired
    private UcenterMemberService memberService;

    //跳转
    @GetMapping("callback")
    public String callback(String code,String state){
        try {
            //1.拿着code(这是一个临时票据,类似于验证码)请求微信给的固定地址
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
//        拼接三个参数
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );
            //用httpclient请求拼接好的地址。
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println(accessTokenInfo);
            Gson gson=new Gson();//重json字符串获取openid和token
            HashMap mapAccessToken=gson.fromJson(accessTokenInfo,HashMap.class);//把字符串转化为map
            String access_token=(String)mapAccessToken.get("access_token") ;
            String openid=(String)mapAccessToken.get("openid");

            //把这些数据放到数据库
            UcenterMember member=memberService.getOpenIdMember(openid);
            if(member==null){
                //用access_token和openid请求微信给的固定地
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl=String.format(baseUserInfoUrl,access_token,openid);//拼接
                String userInfo=HttpClientUtils.get(userInfoUrl);//httpclient请求
                System.out.println(userInfo);
                //获取扫码人的信息
                //讲json转化map
                HashMap userInfoMap=gson.fromJson(userInfo,HashMap.class);
                String nickname=(String) userInfoMap.get("nickname");
                String headimgurl=(String) userInfoMap.get("headimgurl");
                member=new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }
            String jwtToken= JwtUtils.getJwtToken(member.getId(),member.getNickname());
            return "redirect:http://localhost:3000?token="+jwtToken;
        }catch (Exception e){
            throw new GuliException(20001,"登录失败");
        }

    }
    //sheng成二维码
    @GetMapping("login")
    public String getWxCode(){
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //进行URLEncode编码
        String redirect_url= ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try{
            redirect_url= URLEncoder.encode(redirect_url,"utf-8");
        } catch (Exception e) {

        }
        String url=String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_REDIRECT_URL,
                "atguili"
        );
        return  "redirect:"+url;


    }
}
